package triperest.servlets;

import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.io.InputStream;
import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import triperest.TriperestUser;
import triperest.Image;

public class SaveImage extends HttpServlet {
	private static final Logger log = Logger.getLogger(SaveImage.class
			.getName());

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		try {
			ServletFileUpload upload = new ServletFileUpload();
			res.setContentType("text/plain");

			TriperestUser user = new TriperestUser(req);

			FileItemIterator iterator = upload.getItemIterator(req);
			while (iterator.hasNext()) {
				FileItemStream item = iterator.next();
				InputStream stream = item.openStream();

				if (item.isFormField()) {
					log.warning("Got a form field: " + item.getFieldName());
				} else {
					log.warning("Got an uploaded file: " + item.getFieldName()
							+ ", name = " + item.getName());

					int len = stream.available();
					byte[] buffer = new byte[len];
					len = stream.read(buffer, 0, buffer.length);
					Image image = new Image(buffer);
					image.setUser(user);
					image.setComment(req.getParameter("comment"));
					image.save();
				}
			}
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}
}
